//Component Object
import { request, uploadFile2, getAliOssToken } from '../../utils/request.js'
import {
  throttle,
  isLogin,
  getAuthSetting,
  openSettingModal,
  getAudioUrl,
  formatSeconds
} from '../../utils/util.js'

const getToken = require('../../aliUtils/token.js').getToken
const SpeechTranscription = require('../../aliUtils/st.js')
const AKID = 'LTAI5tEiVB1fqnVmo2ctMYi2'
const AKKEY = '1USsGGtonGOgPvSNj71kefjTxDT6I7'
const aliSpeechUrl = 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1'
const APPKEY = '8w519vsOlGEdq8LH'
const app = getApp()
// 创建播放器
let naire_audioContext = null
// 已经播放过的音频地址
let playedAudioSrc = {}

// 当前用户和机器人对话列表
let naire_attachVideoContext = null
// 测评引导 接口返回结果
let naire_guideEvaluationResult = null
// 测评回复 接口返回结果
let naire_tempEvaluationResult = null

// 录音相关变量

let naire_showRecordPopTimeHandler = null
let naire_touchStartTimer = null
let naire_st = null
let recordBannerRectTop = 0
let naire_stResult = ''
let naire_tempStResult = ''
let naire_recorderManager = null
let naire_isCancelRecord = false
let naire_requestTimeHandler = null
let naire_timeHander = null
let naire_curSeconds = 0
let topTotalSeconds = 60
let naire_startRecordTimer = null
let getRecordBannerRectTimer = null
let naire_stsFinished = false
// 是不是正在测评
let isInEvaluation = false

// 对话区触摸事件
let chatTouchStartY = 0
let chatTouchEndY = 0
// 用户最后一次输入语音url
let lastUserVoiceUrl = ''
let playAudioTimer = null
// let naire_reqQuestionnaireId = ''
let requestTask = null
let aiOptimizeTimeHandler = null

Page({
  data: {
    
    hasLogin: isLogin() || false,
    hasRecordAuth: false,
    chatPartVisible: true,
    loginDialogVisible: false,
    // 对话区语音相关 对话状态，null，没语音，pending，请求中，completed，请求完成
    _curAudioOwner: 'ai', // visitor 当前播放的音频是机器人还是用户
    aiChatStatus: 'completed',
    visitorChatStatus: null,
    _curAiAudioSrc: '',
    _curVisitorAudioSrc: '',
    curAiAudioDuration: 0, // 当前机器人的音频时长
    curVisitorAudioDuration: 0, // 当前游客的音频时长
    isAiAudioPlaying: false, // 当前机器人的音频是否正在播放
    isVisitorAudioPlaying: false, // 当前机器人的音频是否正在播放
    // 展示内容
    attachContentVisible: false, // 展示内容
    attachContent: {},
    attachVideoIsPlaying: false, // 展示视频是否播放
    isAttachVideoMuted: true,
    // 录音相关
    recordProgressVisible: false,
    willCancelRecord: false,
    _inRecord: false,
    _recordType: 1, // _recordType: 1, // 1实时录音，2录音文件
    _aliToken: '',
    _audioServerPath: '',
    countTimeNum: 11,
    showPureTime: true,
    curTimeStr: formatSeconds(naire_curSeconds),
    limitTimeStr: formatSeconds(topTotalSeconds),
    submitBtnBgWidth: '0%',
    isPerformQuestion: false, // 区分现在是不是展示题，如果是展示题，则禁止用户输入
    curQuestionnaireId:'',
    curQuestionnaireTitle:''
  },
  onShow() {
    console.log('show curQuestionnaireId：',this.data.curQuestionnaireId)
    // let launchOptions = wx.getEnterOptionsSync()
    // console.log('launchOptions:',launchOptions)
    // getAliOssToken()
   
    this.setData({
      hasLogin: isLogin() || false
    })
    this.initAudio()
    lastUserVoiceUrl = ''
    this.getSettingStatus()
  },
  onLoad(options){
    let curQuestionnaireId = ''
    let curQuestionnaireTitle = ''
    console.log('options:',options)
    if(options.questionnaireId !== undefined){
      curQuestionnaireId = options.questionnaireId
    }else {
      let curQuestionnaire = wx.getStorageSync('curQuestionnaire')
      console.log('curQuestionnaire:',curQuestionnaire)
      if(!curQuestionnaire){
        wx.navigateBack()
        return
      }
      curQuestionnaireId = curQuestionnaire.questionnaires.questionnaireId
      curQuestionnaireTitle = curQuestionnaire.questionnaires.title
    }
    this.getAliStsToken()
    this.setData({
      hasLogin: isLogin() || false,
      curQuestionnaireTitle:curQuestionnaireTitle,
      curQuestionnaireId: curQuestionnaireId
    })
    
    this.aiAssessGuide('wanhujiankang11',1) 
  },
  onUnload: function () {
    console.log('questionnaire onUnload')
    this.resetVar()
    // this.closeChatPart()
    this.initCurPageVar()
    this.destoryRecordManger()
    if(requestTask){
      requestTask.abort()
      requestTask = null
    }
    clearTimeout(aiOptimizeTimeHandler)
  },
  onHide() {
    console.log('questionnaire onHide')
    // this.initCurPageVar()
    // 销毁麦克风，要不会跟组件中的麦克风混了
    this.destoryRecordManger()
    if(requestTask){
      requestTask.abort()
      requestTask = null
    }
    clearTimeout(aiOptimizeTimeHandler)
  },
  
  destoryRecordManger() {
    if(naire_recorderManager){
      naire_recorderManager.stop()
      naire_recorderManager = null
    }
  },

  isCurTabVisible() {
    // 此时此时，是不是在显示此tab页
    let currentTab = wx.getStorageSync('currentTab')
    return currentTab == 1
  },
  resetVar() {
    // 清空所有定时器
    console.log('resetVar')
    if (naire_audioContext) {
      naire_audioContext.src = ''
      naire_audioContext.pause()
      naire_audioContext = null
    }
    if (naire_recorderManager) {
      // console.log('naire_recorderManager:',naire_recorderManager)
      naire_recorderManager.stop()
      naire_recorderManager = null
    }
    if (naire_attachVideoContext) {
      naire_attachVideoContext.destroy()
      // naire_attachVideoContext.pause()
      naire_attachVideoContext = null
    }
    if (naire_st) {
      try {
        naire_st.close()
      } catch (error) {
        console.log('close naire_st error:', error)
      }
    }
    naire_showRecordPopTimeHandler = null
    naire_touchStartTimer = null
    recordBannerRectTop = 0
    naire_stResult = ''
    naire_tempStResult = ''
    naire_recorderManager = null
    naire_isCancelRecord = false
    naire_requestTimeHandler = null
    naire_timeHander = null
    naire_curSeconds = 0
    topTotalSeconds = 60
    naire_startRecordTimer = null
    naire_stsFinished = false
    getRecordBannerRectTimer = null
    chatTouchStartY = 0
    chatTouchEndY = 0

    this.setData({
      chatPartVisible: true,
      _curAudioOwner: 'ai',
      aiChatStatus: 'completed',
      visitorChatStatus: null,
      _curAiAudioSrc: '',
      _curVisitorAudioSrc: '',
      curAiAudioDuration: 0, // 当前机器人的音频时长
      curVisitorAudioDuration: 0, // 当前游客的音频时长
      isAiAudioPlaying: false, // 当前机器人的音频是否正在播放
      isVisitorAudioPlaying: false, // 当前机器人的音频是否正在播放

      // 录音相关
      recordProgressVisible: false,
      willCancelRecord: false,
      _inRecord: false,
      _recordType: 1, // _recordType: 1, // 1实时录音，2录音文件
      _aliToken: '',
      _audioServerPath: '',
      countTimeNum: 11,
      showPureTime: true,
      curTimeStr: formatSeconds(naire_curSeconds),
      limitTimeStr: formatSeconds(topTotalSeconds),
      submitBtnBgWidth: '0%',
      isPerformQuestion: false,
      curQuestionnaireTitle:'',
    })
  },
  chatTouchStart(e) {
    // console.log('chatTouchStart e:',e)
    chatTouchStartY = e.touches[0].pageY
  },
  chatTouchEnd(e) {
    // console.log('chatTouchEnd e:',e)
    chatTouchEndY = e.changedTouches[0].pageY
    if (chatTouchEndY - chatTouchStartY > 10) {
      console.log('对话区向下滑动')
      this.closeChatPart()
    }
  },
  initCurPageVar() {
    // 清空所有定时器
    clearTimeout(getRecordBannerRectTimer)
    clearTimeout(naire_startRecordTimer)
    clearTimeout(naire_requestTimeHandler)
    clearTimeout(naire_timeHander)
    clearTimeout(naire_showRecordPopTimeHandler)
    clearTimeout(naire_touchStartTimer)
    clearTimeout(playAudioTimer)
    naire_guideEvaluationResult = null
    naire_tempEvaluationResult = null
    isInEvaluation = false
    lastUserVoiceUrl = ''
    app.globalData.isInEvaluation = false
    this.setData({
      aiChatStatus: 'completed',
      _curAiAudioSrc: '',
      curAiAudioDuration: 0,
      _curVisitorAudioSrc: '',
      curVisitorAudioDuration: 0,
      visitorChatStatus: null,
      attachContentVisible: false,
      isPerformQuestion: false,
      curQuestionnaireTitle:''
    })
    setTimeout(() => {
      this.setData({
        isMuted: false
      })
    }, 0)
  },
  selfShowToast(txt) {
    wx.showToast({
      title: txt,
      icon: 'none',
      duration: 3000
    })
  },
  initRecordManager() {
    console.log('initRecordManager')
    let that = this
    if (!naire_recorderManager) {
      naire_recorderManager = wx.getRecorderManager()
    }
    // console.log('naire_recorderManager:', naire_recorderManager)

    naire_recorderManager.onFrameRecorded(async (res) => {
      // console.log('onFrameRecorded:')
      if (res.isLastFrame) {
        // console.log('naire_recorderManager isLastFrame')
        // 录音超时
        // this.completeRecord()
      }

      if (naire_st && this.data._inRecord) {
        // console.log('send ' + res.frameBuffer)
        try {
          naire_st.sendAudio(res.frameBuffer)
        } catch (error) {
          console.log('naire_st.sendAudio error:', error)
        }
      }
    })
    // 录音结束
    naire_recorderManager.onStop(async (res) => {
      console.log('naire_recorderManager onStop naire_isCancelRecord:', naire_isCancelRecord)

      // 如果是取消的，直接返回，不做任何操作
      if (naire_isCancelRecord) {
        return
      }
      // console.log('naire_curSeconds:',naire_curSeconds)
      // 录音时间太短
      // if (naire_curSeconds < 2) {
      //   that.selfShowToast('录音时间太短了')
      //   return
      // }
      // console.log('录音结束 res:', res)
      // 正常提交
      if (res.tempFilePath) {
        let uploadResUrl = await uploadFile2(res.tempFilePath)
        console.log('uploadResUrl :', uploadResUrl)
        // console.log('naire_curSeconds :', naire_curSeconds)
        that.setData({
          _audioServerPath: uploadResUrl
        })
        // 如果是录音文件则直接提交，如果是实时录音，还要获取录音结果再提交
        // 录音文件
        if (this.data._recordType === 2) {
          that.submitRecordResult()
        } else {
          // that.startAiOptimize()
          // 等当前任务结束之后再操作
          // wx.showLoading({
          //   title: '发送中',
          //   mask: true
          // })
          this.setData({
            visitorChatStatus: 'pending',
            curVisitorAudioDuration: naire_curSeconds
          })
          // 1s后开始提交
          clearTimeout(aiOptimizeTimeHandler)
          aiOptimizeTimeHandler = setTimeout(() => {
            that.startAiOptimize()
          }, 1000)
        }
      }
    })
  },
  showRecordPop() {
    let that = this
    clearTimeout(naire_showRecordPopTimeHandler)
    naire_showRecordPopTimeHandler = setTimeout(() => {
      // console.log('showRecordPop setTimeout')
      that.setData({
        recordProgressVisible: true
      })
      that.getRecordBannerRect()
    }, 500)
  },
  async getRecordBannerRect() {
    if (getRecordBannerRectTimer !== null) {
      return
    }
    let that = this
    // let that = this as any
    return new Promise((resolve) => {
      getRecordBannerRectTimer = setTimeout(() => {
        wx.createSelectorQuery()
          .in(that)
          .select('#recordBanner')
          .boundingClientRect(function (rect) {
            getRecordBannerRectTimer = null
            // console.log('getRecordBannerRect rect:',rect)
            // that.setData({
            //   recordBannerRect: rect
            // })
            if (rect) {
              recordBannerRectTop = rect.top
              resolve(rect.top)
            } else {
              resolve(null)
            }
          })
          .exec()
      }, 1000)
    })
  },
  hideRecordPop() {
    console.log('hideRecordPop')
    clearTimeout(naire_showRecordPopTimeHandler)
    this.setData({
      recordProgressVisible: false
    })
  },
  initRecordState() {
    console.log('initRecordState')
    // 把录音相关状态初始化
    naire_curSeconds = 0
    naire_stResult = ''
    naire_tempStResult = ''
    this.setData({
      curTimeStr: formatSeconds(naire_curSeconds),
      submitBtnBgWidth: '0%',
      showPureTime: true,
      countTimeNum: 11, // 倒计时提示显示的时间
      willCancelRecord: false
    })
    naire_isCancelRecord = false
  },
  startRecordFile() {
    console.log('startRecordFile')
    if (!this.data._inRecord) {
      console.log('点击太快')
      return
    }
    // 初始化录音状态
    this.initRecordState()
    // 显示录音页面
    this.showRecordPop()
    // 开始录音文件
    clearTimeout(naire_startRecordTimer)
    naire_startRecordTimer = setTimeout(() => {
      this.startCountTime()
      // console.log('topTotalSeconds:',topTotalSeconds)
      naire_recorderManager.start({
        duration: topTotalSeconds * 1000,
        sampleRate: 16000,
        format: 'mp3',
        frameSize: 4,
        encodeBitRate: 96000,
        numberOfChannels: 1
      })
    }, 0)
  },
  cancelRecord() {
    console.log('cancelRecord')
    naire_isCancelRecord = true
    this.recordFinish()
  },
  stopCountTime() {
    if (naire_timeHander) {
      clearInterval(naire_timeHander)
    }
  },
  async recordFinish() {
    console.log('recordFinish')
    this.hideRecordPop()
    if (naire_startRecordTimer) {
      clearTimeout(naire_startRecordTimer)
    }
    // 只有实时录音才调用stop
    if (naire_recorderManager) {
      naire_recorderManager.stop()
    }
    if (!this.data._inRecord) {
      return
    }

    // 停止计时
    this.stopCountTime()
    // 录音结束

    this.setData({
      countTimeNum: 11,
      showPureTime: true,
      _inRecord: false
    })

    if (naire_st && naire_st._client) {
      // console.log('recordFinish naire_st close：',naire_st)
      // 延时关闭，避免数据还在传输中就被突然关闭
      try {
        setTimeout(() => {
          naire_st.close()
        }, 500)
      } catch (e) {
        console.log('recordFinish naire_st close error:', e)
      }
    }
    // 删除录音并发
    // this.removeRecordConCurrent()
    // 录音文件直接关闭弹层
    // console.log('recordFinish 类型和时间:',this.data._recordType,naire_curSeconds)

    try {
      // @ts-ignore
      wx.setPageStyle({
        style: {
          overflow: 'auto' // ‘auto’
        }
      })
    } catch (error) {}
  },
  removeRecordConCurrent() {
    let openid = wx.getStorageSync('openid')
    if (openid) {
      // 获取录音并发
      request({
        url: '/records/remove-real-time?key=' + openid,
        method: 'post',
        success(data) {
          console.log('删除录音并发')
        },
        fail(error) {
          console.log('删除录音并发失败：', error)
        }
      })
    }
  },

  startAiOptimize() {
    let that = this
    if (naire_isCancelRecord) {
      wx.hideLoading()
      that.hideRecordPop()
      return
    }
    if (naire_stResult === '' && naire_tempStResult === '') {
      naire_stsFinished = false
    }
    that.submitRecordResultRealTime()
  },
  submitRecordResult() {
    let that = this
    if (!naire_requestTimeHandler) {
      naire_requestTimeHandler = setTimeout(() => {
        naire_requestTimeHandler = null
      }, 1000)
      this.userInput(content, 2, this.data._audioServerPath)
      naire_requestTimeHandler = null
      that.hideRecordPop()
    }
  },
  submitRecordResultRealTime() {
    // console.log('naire_requestTimeHandler:',naire_requestTimeHandler)
    // console.log('submitRecordResultRealTime:',naire_stResult,this.data._audioServerPath)
    let that = this
    if (!naire_requestTimeHandler) {
      naire_requestTimeHandler = setTimeout(() => {
        naire_requestTimeHandler = null
      }, 100)
      // this.stopAllAudio()
      // 如果录音转文字完成了，就用文本，否则用音频
      let contentType = naire_stsFinished ? 1 : 2
      this.userInput(naire_stResult, contentType, this.data._audioServerPath)
      naire_requestTimeHandler = null
      that.hideRecordPop()
      wx.hideLoading()
    }
  },
  async mainTouchEnd(event) {
    let that = this
    clearTimeout(naire_showRecordPopTimeHandler)
    clearTimeout(naire_touchStartTimer)
    // console.log('mainTouchEnd this.data._inRecord:',this.data._inRecord)
    if (event.target.id === 'authRecordBtn' && that.data._inRecord) {
      // 马上隐藏录音弹窗
      this.hideRecordPop()
      if (!recordBannerRectTop) {
        await that.getRecordBannerRect()
      }
      console.log('recordBannerRectTop:', recordBannerRectTop)
      if (!recordBannerRectTop) {
        // @ts-ignore
        that.selfShowToast('录音时间太短了')
        this.cancelRecord()
        return
      }
      let touch = event.changedTouches[0]
      let pageY = touch.pageY
      // console.log('pageY:',pageY,',recordBannerRect.top:',recordBannerRect.top)

      if (pageY < recordBannerRectTop) {
        this.cancelRecord()
      } else {
        this.recordFinish()
      }
    }
  },

  async mainTouchMove(event) {
    if (!this.data.recordProgressVisible) {
      return
    }
    // console.log('mainTouchMove:',event)
    let that = this
    // console.log('mainTouchMove:',event.target.id,)
    if (event.target.id === 'authRecordBtn' && that.data._inRecord) {
      if (!recordBannerRectTop) {
        await that.getRecordBannerRect()
      }
      // console.log('mainTouchMove recordBannerRectTop:',recordBannerRectTop)
      if (!recordBannerRectTop) {
        return
      }
      let touch = event.touches[0]
      let pageY = touch.pageY
      if (pageY < recordBannerRectTop - 20) {
        that.setData({
          willCancelRecord: true
        })
      } else {
        that.setData({
          willCancelRecord: false
        })
      }
    }
  },
  catchTouchEnd() {
    // console.log('catchTouchEnd')
    return
  },
  catchTouchMove() {
    return
  },
  // ai语音相关
  // 聊天搜索

  // 测评引导
  async aiAssessGuide(content, contentType = 1, contentUrl) {
    this.hideQuestionAttachContent()
    this.setData({
      isPerformQuestion: false,
      aiChatStatus:'pending'
    })
    // 有上一次返回的结果
    let reqData = {
      content,
      contentType,
      contentUrl
    }
    if (naire_guideEvaluationResult) {
      reqData = {
        ...naire_guideEvaluationResult,
        ...reqData
      }
    } else {
      let questionnaireId = this.data.curQuestionnaireId
      reqData = {
        ...reqData,
        questionnaireId: questionnaireId,
        resourceId: questionnaireId,
        resourceType: 2,
        type: 1,
        workflowStatus: 2
      }
    }
    console.log('questionnaire aiAssessGuide reqData:', reqData)
    requestTask = request({
      url: '/api/questionnaireLaunch/guideEvaluation',
      method: 'POST',
      data: reqData,
      success: (respData, data) => {
        
      
        console.log('aiAssessGuide respData:', respData)
        console.log('aiAssessGuide respMsg:', data.respMsg)
        naire_guideEvaluationResult = respData
        // 返回内容
        // 判断下个用户输入是否需要跳转到测评
        if (respData.workflowStatus === 2) {
          isInEvaluation = true
          app.globalData.isInEvaluation = true
          
          // console.log('respData.workflowStatus:',respData.workflowStatus)
          // this.aiAssess(content, contentType,contentUrl,respData)
        } else if (respData.workflowStatus === 1) {
          isInEvaluation = false
          app.globalData.isInEvaluation = false
          
        }
        // 现在是不是展示题，如果是展示题，则禁止用户输入
        if (respData.questions && respData.questions.questionType == 5) {
          // 展示题
          this.setData({
            isPerformQuestion: true
          })
        } else {
          this.setData({
            isPerformQuestion: false
          })
        }

        // 显示展示内容
        this.showQuestionAttachContent(respData)

        this.playAudio(respData.content, 'ai')
        // 播放返回的语音
        if (respData.doneFlag) {
          console.log('整个流程结束了，不用再往下走了')
        }
      }
    })
  },
  // 测评
  async aiAssess(content, contentType = 1, contentUrl, guideRespData) {
    // console.log('start aiAssess',content, contentType,contentUrl)

    let reqData = {
      content,
      contentType,
      contentUrl
    }
    if (naire_tempEvaluationResult) {
      reqData = {
        ...naire_tempEvaluationResult,
        ...reqData
      }
    } else if (naire_guideEvaluationResult) {
      reqData = {
        ...naire_guideEvaluationResult,
        ...reqData
      }
    } else if (guideRespData) {
      reqData = {
        ...guideRespData,
        ...reqData
      }
    } else {
      let questionnaireId = this.data.curQuestionnaireId
      reqData = {
        ...reqData,
        questionnaireId: questionnaireId,
        resourceId: questionnaireId,
        resourceType: 2,
        type: 1,
        workflowStatus: 2
      }
    }
    this.setData({
      aiChatStatus:'pending'
    })
    console.log('aiAssess reqData:', reqData)
    requestTask = request({
      url: '/api/questionnaireLaunch/startQuestionnaire',
      method: 'POST',
      data: reqData,
      success: (respData, data) => {
        
        console.log('aiAssess respData:', respData)
        console.log('aiAssess respMsg:', data.respMsg)
        naire_tempEvaluationResult = respData
        if (reqData.workflowStatus === 2) {
          isInEvaluation = true
          app.globalData.isInEvaluation = true
          
        } else if (reqData.workflowStatus === 1) {
          isInEvaluation = false
          app.globalData.isInEvaluation = false
          
        }
        if (respData.questions && respData.questions.questionType == 5) {
          // 展示题
          this.setData({
            isPerformQuestion: true
          })
        } else {
          this.setData({
            isPerformQuestion: false
          })
        }

        // 返回内容
        // 播放返回的语音
        this.setData({
          aiChatStatus: 'completed'
        })
        this.playAudio(respData.content, 'ai')
        // 显示展示内容
        this.showQuestionAttachContent(respData)

        if (respData.doneFlag) {
          this.setData({
            isPerformQuestion: false
          })
          console.log('整个流程结束了，不用再往下走了')
        }
      }
    })
  },
  hideQuestionAttachContent() {
    this.setData({
      attachContentVisible: false
    })
  },
  jumpToWebPage(event) {
    console.log('jumpToWebPage event:', event)
    let url = event.currentTarget.dataset.webUrl
    wx.navigateTo({
      url: '/pages/webview/webview?url=' + url
    })
  },
  showQuestionAttachContent(respData) {
    // 如果关闭了对话区，则直接返回
    if (!this.data.chatPartVisible) {
      return
    }
    // 展示默认题目
    if (!respData.questions) {
      this.setData({
        attachContentVisible: false
      })
      return
    }
    // if(respData.questionShows && respData.questionShows.length ===0){
    //   this.setData({
    //     attachContentVisible:true
    //   })
    //   return
    // }
    // nodeFlag 是false，就是没有新内容，则还是展示原来的内容
    // if(!respData.nodeFlag && this.data.attachContentVisible){
    //   return
    // }
    if (respData.questions.showType === 0) {
      this.setData({
        attachContent: {
          type: 'question',
          questionShows: respData.questions.questionTitle
        }
      })
    } else if (respData.questions.showType === 1) {
      // 多图
      this.setData({
        attachContent: {
          type: 'imgs',
          questionShows: respData.questionShows
        }
      })
    } else if (respData.questions.showType === 2) {
      // 视频
      this.setData(
        {
          attachContent: {
            type: 'video',
            questionShows: respData.questionShows[0]
          }
        },
        () => {
          // console.log('attachContent:',this.data.attachContent)
          // this.playAttachedVideo()
        }
      )
    } else if (respData.questions.showType === 3) {
      // 网页
      this.setData({
        attachContent: {
          type: 'web',
          questionShows: respData.questionShows
        }
      })
    }
    this.setData(
      {
        attachContentVisible: true
      }
    )
  },
  userInput(content = '', contentType = 1, contentUrl) {
    if (content === '') {
      contentType = 2
    }
    console.log('userInput:', content, contentType, contentUrl)
    // 模拟用户语音输入信息
    // this.setData({
    //   visitorChatStatus: 'completed',
    //   _curVisitorAudioSrc: contentUrl,
    //   _curAudioOwner: 'visitor'
    // },()=>{
    //   this.playAudio(contentUrl,'visitor')
    // })
    
    // 用户输入不用主动播放
    this.stopAudio()
    let _curVisitorAudioSrc = contentUrl || lastUserVoiceUrl
    console.log('_curVisitorAudioSrc:',_curVisitorAudioSrc)
    console.log('lastUserVoiceUrl:',lastUserVoiceUrl)

    this.setData({
      visitorChatStatus: _curVisitorAudioSrc ? 'completed' : null,
      _curVisitorAudioSrc: _curVisitorAudioSrc,
      _curAudioOwner: 'visitor',
      
    })
    if (contentUrl) {
      lastUserVoiceUrl = contentUrl
    }
    // 如果引导结果存在，且要开启测评流程，则走测评流程
    if (isInEvaluation) {
      this.aiAssess(content, contentType, contentUrl)
    } else {
      // 继续走引导流程
      this.aiAssessGuide(content, contentType, contentUrl)
    }
    
  },
  initAudio() {
    playedAudioSrc = {}
    naire_audioContext = wx.createInnerAudioContext()
    // console.log('naire_audioContext:',naire_audioContext)
    naire_audioContext.onCanplay(() => {
      // console.log('_curAudioOwner:',this.data._curAudioOwner)
      console.log('onCanplay naire_audioContext.duration:', naire_audioContext.duration)
      if(this.data._curAudioOwner === 'ai'){
        if(naire_audioContext.duration > 0){
          this.setData({
            curAiAudioDuration: Math.floor(naire_audioContext.duration)
          })
        }
      }
    })
    naire_audioContext.onTimeUpdate(() => {
      // console.log('onTimeUpdate naire_audioContext.duration:',naire_audioContext.duration)
      if (this.data._curAudioOwner == 'ai') {
        this.setData({
          curAiAudioDuration: Math.floor(naire_audioContext.duration),
          isAiAudioPlaying: true
        })
      } else if (this.data._curAudioOwner == 'visitor') {
        this.setData({
          // curVisitorAudioDuration: Math.floor(naire_audioContext.duration),
          isVisitorAudioPlaying: true
        })
      }
    })
 
    naire_audioContext.onPause(() => {
      // console.log('naire_audioContext onPause')
      this.setData({
        isAiAudioPlaying: false,
        isVisitorAudioPlaying: false
      })
    })
    naire_audioContext.onStop(() => {
      // console.log('naire_audioContext onStop')
      this.setData({
        isAiAudioPlaying: false,
        isVisitorAudioPlaying: false
      })
    })
    naire_audioContext.onEnded(() => {
      // console.log('naire_audioContext onEnded _curAudioOwner:',this.data._curAudioOwner)
      // if(this.data._curAudioOwner === 'ai'){
      //   let ans = '不知道哦'
      //   if(questionIndex ===0){
      //     ans = '苹果'
      //   }else if(questionIndex ===1){
      //     ans = '不知道'
      //   }else if(questionIndex ===2){
      //     ans = '8'
      //   }
      //   questionIndex++
      //   this.userInput(ans,1,'')
      // }
      // 如果当前是展示题，则播放完立马请求下一题
      if (this.data._curAudioOwner === 'ai' && this.data.isPerformQuestion) {
        this.userInput('好的', 1)
      }
      this.setData({
        isAiAudioPlaying: false,
        isVisitorAudioPlaying: false
      })
    })
  },
  async playAudio(audioUrl, type) {
    console.log('playAudio:', audioUrl, type)
    // 如果对话区已经收起了，就不播放语音
    if (!this.data.chatPartVisible) {
      return
    }
    if (!audioUrl) {
      return
    }
    if (!this.data.isMuted) {
      this.metedVideo()
    }
    let localSrc = audioUrl
    if (/^http/.test(audioUrl)) {
      localSrc = playedAudioSrc[audioUrl]
      // console.log('inner localSrc:',localSrc)
      if (!localSrc) {
        localSrc = await getAudioUrl(audioUrl)
        playedAudioSrc[audioUrl] = localSrc
      }
    }
    // console.log('localSrc:',localSrc)
    if (!/\.mp3/.test(localSrc)) {
      console.log('localSrc not mp3')
      return
    }
    naire_audioContext.stop()
    naire_audioContext.src = localSrc
    

    if (type === 'ai') {
      this.setData({
        _curAudioOwner: 'ai',
        aiChatStatus: 'completed',
        _curAiAudioSrc: localSrc,
        isAiAudioPlaying: true,
        isVisitorAudioPlaying: false
      })
    } else if (type === 'visitor') {
      this.setData({
        _curAudioOwner: 'visitor',
        visitorChatStatus: 'completed',
        isVisitorAudioPlaying: true,
        isAiAudioPlaying: false
      })
    } else {
      this.setData({
        _curAudioOwner: type,
        isVisitorAudioPlaying: false,
        isAiAudioPlaying: false
      })
    }
    // console.log('naire_audioContext will play')
    clearTimeout(playAudioTimer)
    playAudioTimer = setTimeout(() => {
      naire_audioContext.play()
    }, 300)
  },
  replayAiAudio() {
    if (this.data.aiChatStatus === 'completed') {
      if (this.data.isAiAudioPlaying) {
        this.stopAudio()
      } else {
        let _curAiAudioSrc = this.data._curAiAudioSrc
        this.playAudio(_curAiAudioSrc, 'ai')
      }
    }
  },
  replayCurVisitorAudio() {
    if (this.data.visitorChatStatus === 'completed') {
      if (this.data.isVisitorAudioPlaying) {
        this.stopAudio()
      } else {
        let _curVisitorAudioSrc = this.data._curVisitorAudioSrc
        console.log('_curVisitorAudioSrc:', _curVisitorAudioSrc)
        this.playAudio(_curVisitorAudioSrc, 'visitor')
      }
    }
  },
  stopAudio() {
    naire_audioContext && naire_audioContext.stop()
    this.setData({
      isAiAudioPlaying: false,
      isVisitorAudioPlaying: false
    })
  },
  destoryAudio() {
    console.log('destoryAudio')
    if (naire_audioContext) {
      naire_audioContext.src = ''
      naire_audioContext.stop()
      naire_audioContext.destroy()
    }
    this.setData({
      isAiAudioPlaying: false,
      isVisitorAudioPlaying: false
    })
  },
  loginDialogClose() {
    this.setData({
      loginDialogVisible: false,
      hasLogin: isLogin()
    })
  },
  showLoginDialog() {
    this.stopAudio()
    this.setData({
      loginDialogVisible: true
    })
  },
  initVideoContext() {
    let _videoContext0 = wx.createVideoContext('video0', this)
    let _video1Context1 = wx.createVideoContext('video1', this)
    let _video2Context2 = wx.createVideoContext('video2', this)
    this.data._videoContextList = [
      _videoContext0,
      _video1Context1,
      _video2Context2
    ]
    // console.log('_videoContext0:',_videoContext0)
    // _videoContext0.play()
  },
  agreePrivacyAuthorization() {
    // 用户同意隐私协议
    console.log('用户同意隐私协议2')
  },
  closeChatPart() {
    this.setData({
      chatPartVisible: false,
      isMuted: this.data.attachContentVisible
    })
    this.stopAudio()
  },
  showChatPart() {
    this.setData({
      chatPartVisible: true,
      isMuted: true
    })
    
  },
  changeChatPartVisible() {
    // 对话区是打开的，则关闭
    if (this.data.chatPartVisible) {
      this.closeChatPart()
    } else {
      // 对话区是关闭的，则打开
      this.showChatPart()
    }
  },
  continuePlayAttachVideo() {
    if (this.data.isAttachVideoPlaying) {
    }
  },
  playAttachedVideo() {
    this.stopCurSwiperVideo()
    // console.log('playAttachedVideo naire_attachVideoContext:',naire_attachVideoContext)
    if (!naire_attachVideoContext) {
      naire_attachVideoContext = wx.createVideoContext('attachVideo', this)
    }
    // console.log('playAttachedVideo attachVideoContext2:',naire_attachVideoContext)
    this.stopAudio()
    naire_attachVideoContext.play()
  },
  attachVideoOnPlay() {
    // console.log('attachVideoOnPlay')
    this.setData({
      attachVideoIsPlaying: true
    })
  },

  stopAttachVideo() {
    if (naire_attachVideoContext) {
      naire_attachVideoContext.pause()
    }
    this.setData({
      attachVideoIsPlaying: false
    })
  },
  attachVideoTap() {
    // console.log('attachVideoTap')
    if (!naire_attachVideoContext || naire_attachVideoContext.paused) {
      this.playAttachedVideo()
    } else {
      this.stopAttachVideo()
    }
  },

  getSettingStatus() {
    let that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.record']) {
          that.setData({
            hasRecordAuth: true
          })
          // 初始化录音器
          this.initRecordManager()
        } else {
          that.setData({
            hasRecordAuth: false
          })
        }
      }
    })
  },
  // 获取麦克风权限
  getRecordAuth() {
    console.log('getRecordAuth')
    let that = this
    // 获取麦克风权限
    getAuthSetting(
      'scope.record',
      () => {
        that.setData({
          hasRecordAuth: true
        })
        // 初始化录音器
        this.initRecordManager()
      },
      () => {
        openSettingModal('提示', '请先开启麦克风权限', '去开通')
      }
    )
  },
  metedVideo() {
    // console.log('metedVideo')
    // 静音
    this.setData({
      isMuted: true
    })
  },
  stopAllAudioAndVideo() {
    this.stopAudio()
    this.stopCurSwiperVideo()
    this.stopAttachVideo()
  },
  stopAllAudio() {
    // 静音
    this.metedVideo()
    this.stopAudio()
  },
  recoverMuted() {
    console.log('recoverMuted')
    this.setData({
      isMuted: false
    })
  },
  recoverAttachMuted() {
    console.log('recoverAttachMuted')
    this.setData({
      isAttachVideoMuted: false
    })
  },
  addRecordConCurrent() {
    // 添加录音并发 1=正常 2=已达上限
    return new Promise((resolve) => {
      request({
        url: '/records/add-real-time?key=' + wx.getStorageSync('openid'),
        method: 'post',
        success(data) {
          // 1=正常 2=已达上限
          if (data.status === 1) {
            // 可以实时录音
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail() {
          resolve(false)
        }
      })
    })
  },
  async getAliStsToken() {
    console.log('getAliStsToken')
    let token = await getToken(AKID, AKKEY)
    // console.log('getAliStsToken:',token)
    this.setData(
      {
        _aliToken: token
      },
      () => {
        this.initSpeechTranscription()
      }
    )
  },
  async initSpeechTranscription() {
    // console.log('initSpeechTranscription naire_st:',naire_st)
    // if (naire_st) {
    //   return
    // }

    naire_st = new SpeechTranscription({
      url: aliSpeechUrl,
      appkey: APPKEY,
      token: this.data._aliToken
    })

    naire_st.on('started', (msg) => {
      // console.log('Client recv started',msg)
      // this.setData({
      //   naire_stResult: msg
      // })
    })

    naire_st.on('changed', (res) => {
      // console.log('Client recv changed:', res)
      if (res) {
        try {
          let resObj = JSON.parse(res)
          // console.log('changed resObj:',resObj)
          if (resObj.payload) {
            // that.setData({
            //   naire_tempStResult: resObj.payload.result
            // })
            naire_tempStResult = resObj.payload.result
          }
        } catch (error) {
          console.error(error)
        }
      }
    })

    naire_st.on('completed', (msg) => {
      // console.log('Client recv completed:', msg)
      // this.setData({
      //   naire_stResult: msg
      // })
    })

    naire_st.on('begin', (res) => {
      console.log('naire_st begin')
      // 句子开始
      // console.log('Client recv sentenceBegin:', res)
      naire_stsFinished = false
    })

    naire_st.on('end', (res) => {
      // console.log('Client recv sentenceEnd:', res)
      // 一句话结束
      // this.setData({
      //   naire_stResult: msg
      // })
      console.log('naire_st end')
      naire_stsFinished = true
      if (res) {
        try {
          let resObj = JSON.parse(res)
          // console.log('end Obj:',resObj)
          if (resObj.payload) {
            // that.setData({
            //   naire_stResult: that.data.naire_stResult + resObj.payload.result
            // })
            // console.log('end naire_stResult:',naire_stResult)
            // console.log('resObj.payload.result:',resObj.payload.result)
            let newResult = naire_stResult + resObj.payload.result
            // console.log('newResult:',newResult)
            naire_stResult = newResult
            // that.setData({
            //     naire_stResult: newResult
            //   },()=>{
            //     console.log('end stResult2:',that.data.naire_stResult)
            //   })
          }
        } catch (error) {
          console.error(error)
        }
      }
    })

    naire_st.on('closed', () => {
      console.log('Client recv closed')
    })

    naire_st.on('failed', (msg) => {
      // console.log('Client recv failed:', msg)
      // this.setData({
      //   naire_stResult: msg
      // })
    })
  },
  startCountTime() {
    let that = this
    if (naire_timeHander) {
      clearInterval(naire_timeHander)
    }
    naire_curSeconds = 0
    naire_timeHander = setInterval(() => {
      naire_curSeconds++
      // console.log('naire_curSeconds:',naire_curSeconds)
      if (naire_curSeconds >= topTotalSeconds) {
        clearInterval(naire_timeHander)
        that.recordFinish()
        that.setData({
          submitBtnBgWidth: '100%',
          curTimeStr: formatSeconds(topTotalSeconds)
        })
      } else {
        if (topTotalSeconds - naire_curSeconds <= 10) {
          let countTimeNum = this.data.countTimeNum - 1
          this.setData({
            showPureTime: false,
            countTimeNum
          })
        }
        that.setData({
          submitBtnBgWidth:
            Math.floor((naire_curSeconds / topTotalSeconds) * 100) + '%',
          curTimeStr: formatSeconds(naire_curSeconds)
        })
      }
    }, 1000)
  },
  async startRealTimeRecord() {
    // 开始录音

    if (!this.data._aliToken) {
      await this.getAliStsToken()
    }
    // 开始录音
    if (!naire_st) {
      this.initSpeechTranscription()
    }
    // console.log('startRealTimeRecord naire_recorderManager:',naire_recorderManager)
    if (!naire_recorderManager) {
      this.initRecordManager()
    }

    //
    // console.log('_inRecord:',this.data._inRecord)
    if (!this.data._inRecord) {
      console.log('startRealTimeRecord _inRecord 点击太快')
      // 正在记录，避免重复打开多次
      return
    }
    console.log('开始实时录音')
    this.showRecordPop()

    this.initRecordState()
    this.startCountTime()
    let defaultStartParams = naire_st.defaultStartParams()
    // console.log('defaultStartParams:',defaultStartParams)
    try {
      await naire_st.start(defaultStartParams)
    } catch (error) {
      console.log('startRealTimeRecord error:', error)
    }

    // console.log('topTotalSeconds:',topTotalSeconds)
    naire_recorderManager.start({
      duration: topTotalSeconds * 1000,
      sampleRate: 16000,
      format: 'mp3',
      frameSize: 4,
      encodeBitRate: 96000,
      numberOfChannels: 1
    })
  },
  async authRecord() {
    

    if (!this.data._inRecord) {
      // console.log('authRecord')

      clearTimeout(naire_touchStartTimer)
      naire_touchStartTimer = setTimeout(async () => {
        this.stopAllAudio()
        this.playAudio(
          'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-douwei/longpresson.mp3',
          'tip'
        )
        // console.log('timeout authRecord')
        // 先不管并发
        // let canRealTimeRecord = await this.addRecordConCurrent()
        let canRealTimeRecord = true
        // canRealTimeRecord = false
        if (canRealTimeRecord) {
          this.setData(
            {
              _recordType: 1,
              _inRecord: true
            },
            () => {
              clearTimeout(naire_startRecordTimer)
              naire_startRecordTimer = setTimeout(() => {
                this.startRealTimeRecord()
              }, 100)
            }
          )
        } else {
          this.setData(
            {
              _recordType: 2,
              _inRecord: true
            },
            () => {
              clearTimeout(naire_startRecordTimer)
              naire_startRecordTimer = setTimeout(() => {
                this.startRecordFile()
              }, 100)
            }
          )
        }
        // 设置overflow 禁止页面滚动
        try {
          // @ts-ignore
          wx.setPageStyle({
            style: {
              overflow: 'hidden' // ‘auto’
            }
          })
        } catch (error) {}
      }, 600)
    }
  },
  cancelAuthRecord() {
    console.log('cancelAuthRecord')
    clearTimeout(naire_touchStartTimer)
    this.hideRecordPop()
    if(naire_recorderManager){
      naire_recorderManager.stop()
    }
  },
  onShareAppMessage(){
    return {
      title: this.data.curQuestionnaireTitle,
      path: '/pages/questionnaire/questionnaire?questionnaireId=' + this.data.curQuestionnaireId
    }
  }
})
